# -*- coding: utf-8 -*-
"""
@Time ： 2022/12/27 11:27
@Auth ： jiraWu
@File ：main.py
@IDE ：PyCharm
@Motto:人生苦短，我学Python

"""
import json
import time

"""
爬虫联合数据库
"""
from jira_wu_dev_utils._request import PostRequest, GetRequest
from jira_wu_dev_utils._mysql_db import DB
from winsound import Beep


def create_table():
    conn = DB().conn('pymysql')
    cursor = conn.cursor()
    sql = """
    create table kdj(rownum int,storeName varchar(100)
    ,addressDetail varchar(100),pro varchar(100),provinceName varchar(10),cityName varchar(10));
    """
    cursor.execute(sql)
    print(conn.get_host_info())
    conn.close()


url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
headers = {
    'Cookie': 'route-cell=ksa; ASP.NET_SessionId=l5y24ysh4jrt2zncomf1y1vs; Hm_lvt_1039f1218e57655b6677f30913227148=1672054633; Hm_lpvt_1039f1218e57655b6677f30913227148=1672054633; SERVERID=825676b1eb536df327d3ca8f626c0188|1672055042|1672054633',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}


def get_cont(page: int) -> list:
    global url, headers
    data = {
        'cname': '广州',
        'pid': '',
        'pageSize': 10,
        'pageIndex': page
    }
    cont = PostRequest(url=url, data=data, headers=headers).send_req()  # json字符串
    obj = json.loads(cont)  # 序列化json对象
    return obj['Table1']


def write_db(cont: list) -> bool:
    try:
        conn = DB().conn('pymysql')
        cursor = conn.cursor()
        for row in cont:
            sql = f"""
            insert into kdj(rownum,storeName,addressDetail,pro,provinceName,cityName)
            values({int(row['rownum'])},'{row['storeName']}','{row['addressDetail']}','{row['pro']}','{row['provinceName']}','{row['cityName']}');
            """
            cursor.execute(sql)
        conn.close()
    except Exception as e:
        print("系统维护中...", e)
        return False
    else:
        return True
    finally:
        time.sleep(1)
        print("------------------")


if __name__ == '__main__':
    # 创建数据表
    # create_table()
    err = 0
    succ = 0
    page_start = int(input('起始页码：'))
    page_end = int(input('结束页码：'))
    for page in range(page_start, page_end + 1):
        cont = get_cont(page)
        flag = write_db(cont)
        if not flag:
            print(f'第{page}页数据写入失败')
            err += 1
            continue
        else:
            Beep(2000, 100)
            print(f'第{page}页数据写入成功')
            succ += 1
    print(f"共{page_end}页数据,{succ}页写入成功,{err}页写入失败")
    # GetRequest(url='https://scpic1.chinaz.net/files/default/imgs/2022-10-24/f2cf9c9ac8488ecb_s.jpg'
    #            ).down_load_file(filename=f'素材/1.jpg')
